package com.alibaba.citrus.cr.unified.inventory.facade.service;


import com.alibaba.citrus.cr.common.annotation.FacadeInvoker;
import com.alibaba.citrus.cr.common.constant.SaleOrderConstants;
import com.alibaba.citrus.cr.common.util.TimeUtil;
import com.alibaba.citrus.cr.unified.inventory.model.WarehouseInfo;
import com.alibaba.cz.base.tool.FeatureUtil;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.BaselineQueryScItemByPageFromDbRequest;
import com.epoch.app.bcorder.model.dto.BatchQueryWarehouseByIds2Request;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListRequest;
import com.epoch.app.bcorder.model.dto.SearchCargoZoneListResponse;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryOrderListByOrderIdsRequest;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QueryOrderLineListBySubOrderIdListRequest;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QueryOrderLineListBySubOrderIdListResponse;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QueryOrderLineListForRPARequest;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService;
import com.epoch.app.crb2btradecenter.enums.OrderStatus;
import com.epoch.app.crplatformenhance.model.dto.ScItemSDO;
import com.epoch.app.crunifiedinventory.inventoryverify.service.InventoryVerifyService;
import com.epoch.app.crunifiedinventory.inventoryverifyrecord.dto.CreateResponse;
import com.epoch.app.crunifiedinventory.inventoryverifyrecord.model.InventoryVerifyRecord;
import com.epoch.app.crunifiedinventory.inventoryverifyrecord.service.InventoryVerifyRecordService;
import com.epoch.app.crunifiedinventory.inventoryverifyrecorddetail.model.InventoryVerifyRecordDetail;
import com.epoch.app.crunifiedinventory.inventoryverifyrecorddetail.service.InventoryVerifyRecordDetailService;
import com.epoch.app.crunifiedinventory.inventoryverifyresult.model.InventoryVerifyResult;
import com.epoch.app.crunifiedinventory.inventoryverifyresult.service.InventoryVerifyResultService;
import com.epoch.app.crunifiedinventory.model.dto.BusinessInventoryDTO;
import com.epoch.app.crunifiedinventory.model.dto.BusinessStageInventoryDTO;
import com.epoch.app.crunifiedinventory.model.dto.GetBusinessStageInventoryRequest;
import com.epoch.app.crunifiedinventory.model.dto.GetWithholdingInventoryRequest;
import com.epoch.app.crunifiedinventory.model.dto.InventoryVerifyResponse;
import com.epoch.app.crunifiedinventory.model.dto.QueryInventorySumQuantityRequest;
import com.epoch.app.crunifiedinventory.model.dto.QueryInventorySumQuantityResult;
import com.epoch.app.crunifiedinventory.model.dto.StandardInventoryLoadListRequest;
import com.epoch.app.crunifiedinventory.model.enums.FailReasonEnum;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.epoch.app.crunifiedinventory.standardinventory.model.StandardInventory;
import com.epoch.app.crunifiedinventory.standardinventory.service.StandardInventoryService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @description: RPA对账
 * @author: yuhw
 * @date: 2022年11月09日 19:43
 **/
@Service
@Primary
public class InventoryVerifyServiceImpl implements InventoryVerifyService {

    private static final Log log = Log.getLogger(InventoryVerifyServiceImpl.class);


    @Resource
    private StandardInventoryService standardInventoryService;
    @Resource
    private InventoryVerifyRecordService inventoryVerifyRecordService;
    @Resource
    private InventoryVerifyRecordDetailService inventoryVerifyRecordDetailService;
    @Resource
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    private BaseDataService baseDataService;
    @Resource
    private OrderService orderService;
    @Resource
    private OrderLineService orderLineService;
    @Resource
    private CrUnifiedInventoryService crUnifiedInventoryService;
    @Resource
    private InventoryVerifyResultService inventoryVerifyResultService;

    @Resource(name="logsCheckSyncTaskExecutor")
    ThreadPoolTaskExecutor taskExecutor;

    private static final Integer MAX_PAGE_SIZE = 1000;
    private static final Integer MORE_MAX_PAGE_SIZE = 5000;
    private static final Integer PART = 20;
    private static final String SPLIT = "_";
    //仓库档案model
    private static final Integer WAREHOUSE_MODEL = 1;
    //批次库存
    private static final Integer BATCH_INVENTORY = 2;
    //车销库存
    private static final Integer CAR_INVENTORY = 3;
    private static final int VERIFY_SUCCESS = 1;
    private static final int VERIFY_FAIL = 0;


    /**
     * rpa库存校验
     * @return
     */
    @Override
    @FacadeInvoker(value = "RPA对账", errorCode = "OTS-03-005-00-15-100")
    public Result<InventoryVerifyResponse> verify() {
        //获取RPA的库存数据
        List<StandardInventory> standardInventories = getStandardInventories();
        InventoryVerifyResponse response = new InventoryVerifyResponse();
        if (CollectionUtils.isEmpty(standardInventories)){
            log.error("rpa_verify_error_noStandardInventoryData");
            return null;
        }
        //每次对账的结果
        InventoryVerifyResult inventoryVerifyResult = new InventoryVerifyResult();
        //标记这次对账
        String groupFlag = UUID.randomUUID().toString().replaceAll("-", "");
        inventoryVerifyResult.setTotalCount(standardInventories.size());
        inventoryVerifyResult.setGroupFlag(groupFlag);
        inventoryVerifyResult.setStartTime(new Date());
        AtomicInteger successCount = new AtomicInteger(0);
        AtomicInteger failCount = new AtomicInteger(0);
        //获取仓库 获取货品
        Set<String> inventoryCodes = standardInventories.stream().map(StandardInventory::getInventoryCode)
                .filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Map<String, WarehouseInfo> warehouseAreaMap = getWarehouseArea(inventoryCodes);
        Set<String> goodsCodes = standardInventories.stream().map(StandardInventory::getGoodsCode)
                .filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Map<String, ScItemSDO> scItemMap = getScItemMap(goodsCodes);
        //循环比较库存
        List<Future<Boolean>> futureList = Lists.newArrayList();
        for (StandardInventory standardInventory : standardInventories) {
            //多线程对比数据
            try{
                Future<Boolean> future = CompletableFuture.supplyAsync(()->{
                    InventoryVerifyRecord record = new InventoryVerifyRecord();
                    record.setMsgCode(FailReasonEnum.DEFAULT.getCode());
                    //校验RPA基本数据
                    String msg = checkStandardInventory(standardInventory,warehouseAreaMap,scItemMap,record);
                    if (StringUtils.isNotBlank(msg)){
                        failCount.incrementAndGet();
                        //记录对账失败结果
                        writeInventoryVerifyRecord(
                                fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,msg,groupFlag),
                                null);
                        return false;
                    }
                    WarehouseInfo warehouseInfo = warehouseAreaMap.get(standardInventory.getFactoryCode() + SPLIT + standardInventory.getInventoryCode());
                    ScItemSDO scItemSDO = scItemMap.get(standardInventory.getGoodsCode());
                    QueryInventorySumQuantityResult inventory ;
                    try {
                        //根据逻辑仓id 货品id 获取合计库存
                        inventory = getInventory(warehouseInfo.getId(), scItemSDO.getScItemId(),
                                Lists.newArrayList(BATCH_INVENTORY, CAR_INVENTORY));
                        //2022.12.05 修正 如果获取不到库存 且 sap的库存都是0时 就默认 库存项值都为 0
                        if (inventory == null || StringUtils.isAnyBlank(inventory.getWarehouseAreaId(),inventory.getGoodsId())){
                            if (isAllZero(standardInventory)){
                                inventory = init(warehouseInfo.getId(),warehouseInfo.getWarehouseId(),scItemSDO.getScItemId());
                            }else {
                            failCount.incrementAndGet();
                            writeInventoryVerifyRecord(fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,"获取库存统计结果为空",groupFlag));
                            return false;
                            }
                        }
                        log.info("hasInventory:{},{}",warehouseInfo.getId(),scItemSDO.getScItemId());

                    }catch (Throwable e){
                        log.error("getInventory_error",e);
                        failCount.incrementAndGet();
                        writeInventoryVerifyRecord(fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,"获取库存统计结果接口异常",groupFlag));
                        return false;
                    }
                    //对账RPA 和中台库存数据
                    try{
                        boolean verify = verify(standardInventory, inventory,record, warehouseInfo, scItemSDO, groupFlag);
                        if (verify){
                            successCount.incrementAndGet();
                        }else {
                            failCount.incrementAndGet();
                        }
                    }catch (Throwable throwable){
                        failCount.incrementAndGet();
                        log.error("rpa_verify_error",throwable);
                        log.error("rpa_verify_error:groupFlag:{},standardInventory:{},inventory:{},warehouseInfo:{},scItemSDO:{}",
                                groupFlag,
                                JSON.toJSONString(standardInventory),
                                JSON.toJSONString(inventory),
                                JSON.toJSONString(warehouseInfo),
                                JSON.toJSONString(scItemSDO));
                        return false;
                    }
                    return true;
                },taskExecutor);
                futureList.add(future);
            }catch (Throwable e){
                failCount.incrementAndGet();
                log.error("InventoryVerifyServiceImpl_verify_thread_error",e);
            }
//            InventoryVerifyRecord record = new InventoryVerifyRecord();
//            //校验RPA基本数据
//            msg = checkStandardInventory(standardInventory,warehouseAreaMap,scItemMap,record);
//            if (StringUtils.isNotBlank(msg)){
//                failCount.incrementAndGet();
//                writeInventoryVerifyRecord(
//                        fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,msg,groupFlag),
//                        null);
//                continue;
//            }
//            WarehouseInfo warehouseInfo = warehouseAreaMap.get(standardInventory.getFactoryCode() + SPLIT + standardInventory.getInventoryCode());
//            ScItemSDO scItemSDO = scItemMap.get(standardInventory.getGoodsCode());
//            QueryInventorySumQuantityResult inventory ;
//            try {
//                //根据逻辑仓id 货品id 获取合计库存
//                inventory = getInventory(warehouseInfo.getId(), scItemSDO.getScItemId(),
//                        Lists.newArrayList(BATCH_INVENTORY, CAR_INVENTORY));
//                if (inventory == null || StringUtils.isAnyBlank(inventory.getWarehouseAreaId(),inventory.getGoodsId())){
//                    failCount.incrementAndGet();
//                    writeInventoryVerifyRecord(fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,"获取库存统计结果为空",groupFlag));
//                    continue;
//                }
//
//                log.info("hasInventory:{},{}",JSON.toJSONString(warehouseInfo),JSON.toJSONString(scItemSDO));
//
//            }catch (Throwable e){
//                log.error("getInventory_error",e);
//                failCount.incrementAndGet();
//                writeInventoryVerifyRecord(fillInventoryRecordWithStandardInventoryWithMsg(standardInventory,record,"获取库存统计结果接口异常",groupFlag));
//                continue;
//            }
//            //对账RPA 和中台库存数据
//            try{
//                boolean verify = verify(standardInventory, inventory,record, warehouseInfo, scItemSDO, groupFlag);
//                if (verify){
//                    successCount.incrementAndGet();
//                }else {
//                    failCount.incrementAndGet();
//                }
//            }catch (Throwable throwable){
//                failCount.incrementAndGet();
//                log.error("rpa_verify_error",throwable);
//                log.error("rpa_verify_error:groupFlag:{},standardInventory:{},inventory:{},warehouseInfo:{},scItemSDO:{}",
//                        groupFlag,
//                        JSON.toJSONString(standardInventory),
//                        JSON.toJSONString(inventory),
//                        JSON.toJSONString(warehouseInfo),
//                        JSON.toJSONString(scItemSDO));
//            }
        }
        log.info("futureList:{}",futureList.size());
        List<Boolean> list = Lists.newArrayList();
        for (Future<Boolean> booleanFuture : futureList) {
            try {
                Boolean aBoolean = booleanFuture.get();
                list.add(aBoolean);
            } catch (Throwable e) {
                e.printStackTrace();
            }
        }
        System.out.println(JSON.toJSONString(list));
        inventoryVerifyResult.setSuccessCount(successCount.get());
        inventoryVerifyResult.setFailCount(failCount.get());
        inventoryVerifyResult.setEndTime(new Date());
        inventoryVerifyResultService.create(inventoryVerifyResult);
        response.setFailCount(failCount.get());
        response.setSuccessCount(successCount.get());
        return Result.success(response);
    }

    /**
     * 获取RPA库存记录
     * @return
     */
    private List<StandardInventory> getStandardInventories(){
        StandardInventoryLoadListRequest standardInventoryLoadListRequest = new StandardInventoryLoadListRequest();
        Result<List<StandardInventory>> listResult = standardInventoryService.loadList(standardInventoryLoadListRequest);
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            return null;
        }
        int total = listResult.getTotal();
        //循环获取rpa库存记录
        int page = total % MAX_PAGE_SIZE == 0 ?total / MAX_PAGE_SIZE : total / MAX_PAGE_SIZE + 1;
        List<StandardInventory> standardInventories = Lists.newArrayList();
        List<Future<List<StandardInventory>>> futureList = Lists.newArrayList();
        for (int i =0;i < page ; i++){
            final int finalStartPage = i;
            StandardInventoryLoadListRequest request = new StandardInventoryLoadListRequest();
            CompletableFuture<List<StandardInventory>> future = CompletableFuture.supplyAsync(()->{
                request.setStart(finalStartPage * MAX_PAGE_SIZE);
                request.setLimit(MAX_PAGE_SIZE);
                Result<List<StandardInventory>> result = standardInventoryService.loadList(request);
                if (result == null || CollectionUtils.isEmpty(result.getResult())){
                    return Lists.newArrayList();
                }
                return result.getResult();
            },taskExecutor);
            futureList.add(future);
        }
        for (Future<List<StandardInventory>> future : futureList) {
            try{
                List<StandardInventory> inventories = future.get();
                if (CollectionUtils.isNotEmpty(inventories)){
                    standardInventories.addAll(inventories);
                }
            }catch (Throwable e){
                log.error("getStandardInventories_thread_error",e);
            }
        }
        return standardInventories;
    }

    /**
     * 获取逻辑仓库信息
     * @param inventoryCodes
     * @return
     */
    private Map<String, WarehouseInfo> getWarehouseArea(Set<String> inventoryCodes){
        Map<String,WarehouseInfo> warehouseInfoMap = Maps.newHashMap();
        List<String> inventoryCodeList = new ArrayList<>(inventoryCodes);
        List<List<String>> inventoryCodePartition = Lists.partition(inventoryCodeList, PART);
        for (List<String> list : inventoryCodePartition) {
            SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
            searchCargoZoneListRequest.setStatus(1);
            searchCargoZoneListRequest.setWarehouseCodes(list);
            searchCargoZoneListRequest.setLimit(MAX_PAGE_SIZE);
            SearchCargoZoneListResponse response =
                    unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
            if (response != null && CollectionUtils.isNotEmpty(response.getResult())){
                List<com.epoch.app.bcorder.model.dto.WarehouseInfo> result = response.getResult();
                List<WarehouseInfo> warehouseInfosResult = convert(result,WarehouseInfo.class);
                //获取到 工厂编码_库存地点 -> 仓库信息
                warehouseInfosResult.forEach(warehouseInfo -> warehouseInfoMap.put(warehouseInfo.getSapFactoryCode() + SPLIT +  warehouseInfo.getWarehouseCode(),
                        warehouseInfo));

            }
        }
        if (!warehouseInfoMap.isEmpty()){
            fillWarehouseInfo(warehouseInfoMap);
        }
        return warehouseInfoMap;
    }

    /**
     * 补充仓库档案信息
     * @param warehouseInfoMap
     */
    private void fillWarehouseInfo(Map<String,WarehouseInfo> warehouseInfoMap){
        //获取到仓库档案id
        List<String> warehouseIdList = warehouseInfoMap.values().stream()
                .map(WarehouseInfo::getWarehouseId).distinct().collect(Collectors.toList());
        //仓库档案数量较少直接分页
        BatchQueryWarehouseByIds2Request request = new BatchQueryWarehouseByIds2Request();
        request.setWarehouseIds(warehouseIdList);
        request.setModelList(Lists.newArrayList(WAREHOUSE_MODEL));
        Result<List<com.epoch.app.bcorder.model.dto.WarehouseInfo>> warehouseList = unifiedInventoryService.batchQueryWarehouseByIds2(request);
        if (warehouseList != null && CollectionUtils.isNotEmpty(warehouseList.getResult())){
//            Map<String, List<com.epoch.app.bcorder.model.dto.WarehouseInfo>> warehouseMap = warehouseList.getResult().stream().collect(Collectors.groupingBy(com.epoch.app.bcorder.model.dto.WarehouseInfo::getId));
            Map<String, com.epoch.app.bcorder.model.dto.WarehouseInfo> warehouseMap = warehouseList.getResult().stream()
                    .collect(Collectors.toMap(com.epoch.app.bcorder.model.dto.WarehouseInfo::getId, a -> a, (a, b) -> a));
            warehouseInfoMap.values().forEach(v -> {
                if (warehouseMap.get(v.getWarehouseId()) != null){
                    v.setWarehouseName(warehouseMap.get(v.getWarehouseId()).getName());
                    v.setWarehouseMainCode(warehouseMap.get(v.getWarehouseId()).getCode());
                }
            });
        }
    }

    /**
     * 根据货品编码 查询货品
     * @param goodsCodes
     * @return
     */
    private Map<String,ScItemSDO> getScItemMap(Set<String> goodsCodes){
        Map<String,ScItemSDO> scItemSDOMap = Maps.newHashMap();
        if (CollectionUtils.isEmpty(goodsCodes)){
            return scItemSDOMap;
        }
        List<String> goodsCodeList = new ArrayList<>(goodsCodes);
        BaselineQueryScItemByPageFromDbRequest request = new BaselineQueryScItemByPageFromDbRequest();
        request.setOutIdList(goodsCodeList);
        request.setLimit(goodsCodeList.size() > MAX_PAGE_SIZE ? MORE_MAX_PAGE_SIZE: MAX_PAGE_SIZE);
        request.setStatusList(Lists.newArrayList(1,-1));
        Object data = baseDataService.baselineQueryScItemByPageFromDb(request);
        List<ScItemSDO> scItemSDOS = convertResult2ScItemSDOList(data);
        if (CollectionUtils.isNotEmpty(scItemSDOS)){
            scItemSDOMap = scItemSDOS.stream().collect(Collectors.toMap(ScItemSDO::getOuterId,a->a,(a,b)->a));
        }
        return scItemSDOMap;
    }

    /**
     * 中台货品转换
     * @param data
     * @return
     */
    private List<ScItemSDO> convertResult2ScItemSDOList(Object data){
        if (data == null){
            return null;
        }
        JSONObject object = JSON.parseObject(JSON.toJSONString(data));
        if (object == null){
            return null;
        }
        JSONObject result = object.getJSONObject("result");
        if (result == null){
            return null;
        }
        JSONObject resultJSONObject = result.getJSONObject("result");
        if (resultJSONObject == null){
            return null;
        }
        JSONArray content = resultJSONObject.getJSONArray("content");
        if (content == null || content.size() ==0){
            return null;
        }
        List<ScItemSDO> scItemSDOS = Lists.newArrayList();
        for (int i = 0; i < content.size(); i++) {
            JSONObject jsonObject = content.getJSONObject(i);
            scItemSDOS.add(scItemConverter(jsonObject));
        }
        return scItemSDOS;
    }
    /**
     * 货品模型转换
     * **/
    private ScItemSDO scItemConverter(JSONObject obj) {
        ScItemSDO scItemSDO = new ScItemSDO();
        scItemSDO.setBarCode(obj.getString("barCode"));
        // 这里需要查询品牌
        scItemSDO.setBrandId(obj.getString("brandId"));
        scItemSDO.setScItemId(obj.getString("scItemId"));
        scItemSDO.setLeafCategoryId(obj.getString("leafCategoryId"));
        //  实际蒙牛货品的很多字段都在features中
        scItemSDO.setFeatures((Map) obj.get("features"));
        scItemSDO.setOuterId(obj.getString("outerId"));
        scItemSDO.setTitle(obj.getString("title"));
        scItemSDO.setType(Integer.getInteger(obj.getString("type")));
        scItemSDO.setUnit(obj.getString("unit"));
        scItemSDO.setStatus(Objects.isNull(obj.getString("status")) ? -1 : Double.valueOf(obj.getString("status")).intValue());
        if (Objects.nonNull(obj.getString("gmtModified"))) {
            String gmtModifiedStr = obj.getString("gmtModified");
            Date gmtModified = TimeUtil.parseTime(gmtModifiedStr);
            scItemSDO.setGmtModified(gmtModified);
        }
        if (Objects.nonNull(obj.getString("gmtCreate"))) {
            String gmtCreateStr = obj.getString("gmtCreate");
            Date gmtCreate = TimeUtil.parseTime(gmtCreateStr);
            scItemSDO.setGmtCreate(gmtCreate);
        }
        return scItemSDO;
    }

    /**
     *  获取仓库库存 库存的接口返回和页面一致
     * @param warehouseAreaId
     * @param goodsId
     * @param types
     */
    private QueryInventorySumQuantityResult getInventory(String warehouseAreaId, String goodsId, List<Integer> types){
        QueryInventorySumQuantityRequest request = new QueryInventorySumQuantityRequest();
        request.setWarehouseAreaId(warehouseAreaId);
        request.setGoodsId(goodsId);
        if (CollectionUtils.isNotEmpty(types)){
            request.setTypes(types);
        }
        Result<QueryInventorySumQuantityResult> result = crUnifiedInventoryService.queryInventorySumQuantity(request);
        return  result.getResult();
    }


    /**
     * 检查RPA库存数据
     * @param standardInventory
     * @param warehouseAreaMap
     * @param scItemMap
     * @return
     */
    private String checkStandardInventory(StandardInventory standardInventory,
                           Map<String, WarehouseInfo> warehouseAreaMap,
                           Map<String, ScItemSDO> scItemMap,
                                          InventoryVerifyRecord record){
        String msg = null;
        if (StringUtils.isBlank(standardInventory.getFactoryCode())){
            msg = "工厂编码为空";
            return msg;
        }
        if (StringUtils.isBlank(standardInventory.getInventoryCode())){
            msg = "库存地点为空";
            return msg;
        }
        WarehouseInfo warehouseInfo = warehouseAreaMap.get(standardInventory.getFactoryCode() + SPLIT + standardInventory.getInventoryCode());
        if (warehouseInfo == null){
            msg = String.format("工厂编码%s库存地点%s匹配逻辑仓库失败",standardInventory.getFactoryCode(),standardInventory.getInventoryCode());
            return msg;
        }
        record.setWarehouseAreaId(warehouseInfo.getId());
        record.setWarehouseAreaName(warehouseInfo.getName());
        record.setWarehouseAreaCode(warehouseInfo.getCode());
        record.setWarehouseAreaSaleOrgId(warehouseInfo.getSaleOrgId());
        record.setWarehouseCode(warehouseInfo.getWarehouseMainCode());
        record.setWarehouseId(warehouseInfo.getWarehouseId());
        record.setWarehouseName(warehouseInfo.getWarehouseName());

        if (StringUtils.isBlank(standardInventory.getGoodsCode())){
            msg = "货品编码为空";
            return msg;
        }
        if (scItemMap.get(standardInventory.getGoodsCode()) == null){
            msg = String.format("货品编码%s匹配货品失败",standardInventory.getGoodsCode());
            return msg;
        }
        record.setGoodsId(scItemMap.get(standardInventory.getGoodsCode()).getScItemId());
        fillStandardInventory(standardInventory);
        if (!checkQuantity(standardInventory.getAvailableQuantity())
            || !checkQuantity(standardInventory.getWithholdingQuantity())
            || !checkQuantity(standardInventory.getInspectQuantity())
            || !checkQuantity(standardInventory.getFrozenQuantity())
            || !checkQuantity(standardInventory.getUnrestrictedQuantity())){
            msg = "库存数量非数字格式";
            return msg;
        }
        return msg;
    }

    /**
     * 对比RPA库存和中台库存
     * @param standardInventory
     * @param result
     */
    private boolean verify(StandardInventory standardInventory, QueryInventorySumQuantityResult result,
                           InventoryVerifyRecord record,
                                   WarehouseInfo warehouseInfo, ScItemSDO scItemSDO,String groupFlag){
        boolean flag = false;
        //填充数据
        fillInventoryVerifyRecord(standardInventory,result,record,warehouseInfo,scItemSDO,groupFlag);
        //设置校验状态
        setVerifyStatus(record);
        List<InventoryVerifyRecordDetail> details = Lists.newArrayList();
        //如果占用数量不匹配 需要查询预占
        if (record.getWithholdingQuantityVerifyStatus() != VERIFY_SUCCESS){
            List<BusinessInventoryDTO> withholdingInventoryList;
            try{
                //根据仓库id 和 货品id 获取有预占库存的库存记录
                withholdingInventoryList = getWithholdingInventory(record.getWarehouseAreaId(), record.getGoodsId(),
                        Lists.newArrayList(BATCH_INVENTORY,CAR_INVENTORY));
            }catch (Throwable e){
                log.error("verify_getWithholdingInventory_error",e);
                record.setMsg(e.getMessage());
                writeInventoryVerifyRecord(record,null);
                return false;
            }

            if (CollectionUtils.isNotEmpty(withholdingInventoryList)){
                List<Long> inventoryIds = withholdingInventoryList.stream().map(BusinessInventoryDTO::getId).collect(Collectors.toList());
                List<BusinessStageInventoryDTO> businessStageInventoryList;
                try {
                    //根据库存id列表获取库存预占记录
                    businessStageInventoryList = getBusinessStageInventory(inventoryIds);
                }catch (Throwable e){
                    log.error("verify_getBusinessStageInventory_error",e);
                    record.setMsg(e.getMessage());
                    writeInventoryVerifyRecord(record,null);
                    return false;
                }
                if (CollectionUtils.isNotEmpty(businessStageInventoryList)){
                    List<String> orderIds = businessStageInventoryList.stream().map(BusinessStageInventoryDTO::getReferenceOrderId)
                            .distinct().collect(Collectors.toList());
//                    List<String> subOrderIds = businessStageInventoryList.stream().map(BusinessStageInventoryDTO::getReferenceSubOrderId)
//                            .distinct().collect(Collectors.toList());
//                    QueryOrderLineListBySubOrderIdListRequest subOrderIdListRequest = new QueryOrderLineListBySubOrderIdListRequest();
//                    subOrderIdListRequest.setSubOrderIdList(subOrderIds);
//                    subOrderIdListRequest.setLimit(MAX_PAGE_SIZE);
                    //查询到子单合集
//                    QueryOrderLineListBySubOrderIdListResponse orderLineResult =
//                            orderLineService.queryOrderLineListBySubOrderIdList(subOrderIdListRequest);
                    QueryOrderLineListForRPARequest queryOrderLineListForRPARequest = new QueryOrderLineListForRPARequest();
                    queryOrderLineListForRPARequest.setMainOrderIdList(orderIds);
                    queryOrderLineListForRPARequest.setLineStatusList(Lists.newArrayList(
                            OrderStatus.STAY_PUSH.getCode(),
                            OrderStatus.PUSHING.getCode(),
                            OrderStatus.BEFORE_DELIVERY.getCode()));
                    queryOrderLineListForRPARequest.setScItemId(result.getGoodsId());
                    queryOrderLineListForRPARequest.setLimit(MAX_PAGE_SIZE);
                    //根据货品id 和主单id集合 查询子单列表 (待推送 已推送 待交货的)
                    Result<List<OrderLine>> orderLineResult = orderLineService.queryOrderLineListForRPA(queryOrderLineListForRPARequest);
                    if (orderLineResult != null && CollectionUtils.isNotEmpty(orderLineResult.getResult())){
                        List<OrderLine> orderLineList = orderLineResult.getResult().stream()
                                .filter(InventoryVerifyServiceImpl::filter).collect(Collectors.toList());
                        if (CollectionUtils.isNotEmpty(orderLineList)){
                            Map<Long, Order> orderMap = Maps.newHashMap();
                            QueryOrderListByOrderIdsRequest orderIdsRequest = new QueryOrderListByOrderIdsRequest();
                            orderIdsRequest.setOrderIdList(orderIds);
                            orderIdsRequest.setLimit(MAX_PAGE_SIZE);
                            //根据子单列表上的主单id集合查询主单列表
                            Result<List<Order>> orderResult = orderService.queryOrderListByOrderIds(orderIdsRequest);
                            if (orderResult != null && CollectionUtils.isNotEmpty(orderResult.getResult())){
                                orderMap = orderResult.getResult().stream().collect(Collectors.toMap(Order::getId, x -> x, (a, b) -> a));
                            }
                            for (OrderLine orderLine : orderLineList) {
                                InventoryVerifyRecordDetail detail = new InventoryVerifyRecordDetail();
                                fillInventoryVerifyRecordDetail(detail,orderLine,orderMap.get(Long.parseLong(orderLine.getMainOrderId())),
                                        warehouseInfo,
                                        scItemSDO,
                                        groupFlag);
                                details.add(detail);
                            }
                        }
                    }

                }
            }
        }
        writeInventoryVerifyRecord(record,details);
        if (record.getVerifyStatus() == VERIFY_SUCCESS){
            flag = true;
        }
        return flag;
    }

    /**
     * 剔除掉 待交货状态下 且有交货单号的子单
     * @param orderLine
     * @return
     */
    private static boolean filter(OrderLine orderLine){
        if (!orderLine.getStatus().equals(OrderStatus.BEFORE_DELIVERY.getCode())){
            return true;
        }
        String features = orderLine.getFeatures();
        if (StringUtils.isBlank(features)){
            return true;
        }
        Map<String, String> featureMap = JSONObject.parseObject(orderLine.getFeatures(), Map.class);
        if (featureMap == null || featureMap.isEmpty()){
            return true;
        }
        return StringUtils.isBlank(featureMap.get(SaleOrderConstants.DELIVERY_ORDER_ID));
    }

    /** 如果数量为空 填充0 **/
    void fillStandardInventory(StandardInventory standardInventory){
        if (StringUtils.isBlank(standardInventory.getAvailableQuantity())){
            standardInventory.setAvailableQuantity("0");
        }
        if (StringUtils.isBlank(standardInventory.getWithholdingQuantity())){
            standardInventory.setWithholdingQuantity("0");
        }
        if (StringUtils.isBlank(standardInventory.getFrozenQuantity())){
            standardInventory.setFrozenQuantity("0");
        }
        if (StringUtils.isBlank(standardInventory.getUnrestrictedQuantity())){
            standardInventory.setUnrestrictedQuantity("0");
        }
        if (StringUtils.isBlank(standardInventory.getInspectQuantity())){
            standardInventory.setInspectQuantity("0");
        }
    }

    InventoryVerifyRecord fillInventoryVerifyRecord(StandardInventory standardInventory, QueryInventorySumQuantityResult result,
                                                    InventoryVerifyRecord record,
                                                    WarehouseInfo warehouseInfo, ScItemSDO scItemSDO,String groupFlag){
        //可用库存除以1000 - rpa库存
        String availableQuantityDiff = getDiff(result.getAvailableQuantity(), standardInventory.getAvailableQuantity());
        String withholdingQuantityDiff  = getDiff(result.getWithholdingQuantity(), standardInventory.getWithholdingQuantity());
        String inspectQuantityDiff = getDiff(result.getInspectQuantity(), standardInventory.getInspectQuantity());
        String frozenQuantityDiff = getDiff(result.getFrozenQuantity(), standardInventory.getFrozenQuantity());
        // 平台非限制库存 = 总库存-平台冻结库存-平台质检库存
        //2022.12.07 产品修正 平台非限制应该是总数量 - 2*(冻结+质检)
        Long unrestrictedQuantity = result.getTotalQuantity() - 2L * result.getFrozenQuantity() - 2L * result.getInspectQuantity();
        String unrestrictedQuantityDiff = getDiff(unrestrictedQuantity
                , standardInventory.getUnrestrictedQuantity());

        Integer availableQuantityVerifyStatus = getStatus(availableQuantityDiff);
        Integer withholdingQuantityVerifyStatus = getStatus(withholdingQuantityDiff);
        Integer inspectQuantityVerifyStatus = getStatus(inspectQuantityDiff);
        Integer frozenQuantityVerifyStatus = getStatus(frozenQuantityDiff);
        Integer unrestrictedQuantityVerifyStatus = getStatus(unrestrictedQuantityDiff);

        if (record == null){
            record = new InventoryVerifyRecord();
        }
        record.setStandardAvailableQuantity(standardInventory.getAvailableQuantity());
        record.setStandardWithholdingQuantity(standardInventory.getWithholdingQuantity());
        record.setStandardInspectQuantity(standardInventory.getInspectQuantity());
        record.setStandardFrozenQuantity(standardInventory.getFrozenQuantity());
        record.setStandardUnrestrictedQuantity(standardInventory.getUnrestrictedQuantity());

        record.setAvailableQuantity(zoomOutOneThousand(result.getAvailableQuantity()));
        record.setWithholdingQuantity(zoomOutOneThousand(result.getWithholdingQuantity()));
        record.setFrozenQuantity(zoomOutOneThousand(result.getFrozenQuantity()));
        record.setInspectQuantity(zoomOutOneThousand(result.getInspectQuantity()));
        record.setUnrestrictedQuantity(zoomOutOneThousand(unrestrictedQuantity));
        record.setTotalQuantity(zoomOutOneThousand(result.getTotalQuantity()));

        record.setAvailableQuantityDifference(availableQuantityDiff);
        record.setWithholdingQuantityDifference(withholdingQuantityDiff);
        record.setFrozenQuantityDifference(frozenQuantityDiff);
        record.setInspectQuantityDifference(inspectQuantityDiff);
        record.setUnrestrictedQuantityDifference(unrestrictedQuantityDiff);

        record.setAvailableQuantityVerifyStatus(availableQuantityVerifyStatus);
        record.setWithholdingQuantityVerifyStatus(withholdingQuantityVerifyStatus);
        record.setInspectQuantityVerifyStatus(inspectQuantityVerifyStatus);
        record.setFrozenQuantityVerifyStatus(frozenQuantityVerifyStatus);
        record.setUnrestrictedQuantityVerifyStatus(unrestrictedQuantityVerifyStatus);


        record.setFactoryCode(standardInventory.getFactoryCode());
        record.setInventoryCode(standardInventory.getInventoryCode());
        record.setWarehouseId(warehouseInfo.getWarehouseId());
        record.setWarehouseCode(warehouseInfo.getWarehouseMainCode());
        record.setWarehouseName(warehouseInfo.getWarehouseName());
        record.setWarehouseAreaId(warehouseInfo.getId());
        record.setWarehouseAreaName(warehouseInfo.getName());
        record.setWarehouseAreaCode(warehouseInfo.getCode());
        record.setWarehouseAreaSaleOrgId(warehouseInfo.getSaleOrgId());
        record.setGoodsCode(scItemSDO.getOuterId());
        record.setGoodsId(scItemSDO.getScItemId());


        record.setGroupFlag(groupFlag);
        return  record;
    }

    /** 装配对比异常记录  **/
    void fillInventoryVerifyRecordDetail(InventoryVerifyRecordDetail detail, OrderLine orderLine,
                                         Order order,
                                         WarehouseInfo warehouseInfo, ScItemSDO scItemSDO,String groupFlag){
        detail.setOrderLineId(orderLine.getId());
        detail.setGoodsCode(scItemSDO.getOuterId());
        detail.setGoodsId(scItemSDO.getScItemId());
        detail.setUnit(orderLine.getSaleUnitName());
        detail.setLineNo(StringUtils.isNotBlank(orderLine.getSerialNumber()) ?
                Integer.parseInt(orderLine.getSerialNumber()) : null);
        detail.setOrderLineId(orderLine.getId());
        detail.setLineStatus(orderLine.getStatus());
        detail.setQuantity(orderLine.getQuantity());
        detail.setUnitConvert(orderLine.getUnitConvert());
        if (order != null){
            detail.setOrderId(order.getId());
            detail.setOrderStatus(order.getStatus());
            detail.setOrderCode(order.getOrderBizId());
            detail.setOutOrderId(order.getOuterOrderId());
            detail.setOrderWarehouseAreaId(order.getWareHouseCode());
        }
        detail.setWarehouseAreaId(warehouseInfo.getId());
        detail.setWarehouseAreaName(warehouseInfo.getName());
        detail.setWarehouseAreaCode(warehouseInfo.getCode());
        detail.setWarehouseAreaSaleOrgId(warehouseInfo.getSaleOrgId());
        detail.setWarehouseId(warehouseInfo.getWarehouseId());
        detail.setWarehouseName(warehouseInfo.getWarehouseName());
        detail.setOutLineNo(StringUtils.isNotBlank(orderLine.getOuterOrderLineId()) ? Integer.parseInt(orderLine.getOuterOrderLineId()) : null);

        detail.setGroupFlag(groupFlag);
    }

    // 根据逻辑仓id和货品id获取到库存有预占的库存id
    List<BusinessInventoryDTO> getWithholdingInventory(String warehouseAreaId,String goodsId,List<Integer> types){
        if (StringUtils.isAnyBlank(warehouseAreaId,goodsId)){
            return null;
        }
        GetWithholdingInventoryRequest getWithholdingInventoryRequest = new GetWithholdingInventoryRequest();
        getWithholdingInventoryRequest.setWarehouseAreaId(warehouseAreaId);
        getWithholdingInventoryRequest.setGoodsId(goodsId);
        if (CollectionUtils.isEmpty(types)){
            getWithholdingInventoryRequest.setTypes(Lists.newArrayList(BATCH_INVENTORY,CAR_INVENTORY));
        }else {
            getWithholdingInventoryRequest.setTypes(types);
        }
        Result<List<BusinessInventoryDTO>> withholdingInventory = crUnifiedInventoryService.getWithholdingInventory(getWithholdingInventoryRequest);
        return withholdingInventory.getResult();
    }
    // 根据逻辑仓id和货品id获取到库存有预占的预占列表
    List<BusinessStageInventoryDTO> getBusinessStageInventory(List<Long> inventoryIds){
        if (CollectionUtils.isEmpty(inventoryIds)){
            return null;
        }
        GetBusinessStageInventoryRequest getBusinessStageInventoryRequest = new GetBusinessStageInventoryRequest();
        getBusinessStageInventoryRequest.setInventoryIds(inventoryIds);
        Result<List<BusinessStageInventoryDTO>> businessStageInventory = crUnifiedInventoryService.getBusinessStageInventory(getBusinessStageInventoryRequest);
        return businessStageInventory.getResult();
    }



    /**
     * 写入校验结果*
     * @param record
     * @param details
     */
    private void writeInventoryVerifyRecord(InventoryVerifyRecord record,
                                            List<InventoryVerifyRecordDetail> details){
        if (record  == null){
            record = new InventoryVerifyRecord();
        }
//        if (StringUtils.isNotBlank(msg)){
//            record.setMsg(msg);
//        }
        CreateResponse createResponse = inventoryVerifyRecordService.create(record);
        if (CollectionUtils.isNotEmpty(details)){
            for (InventoryVerifyRecordDetail detail : details) {
                detail.setInventoryVerifyRecordId(createResponse.getLastInsertId());
                inventoryVerifyRecordDetailService.create(detail);
            }
        }
    }
    /** 写入校验结果 **/
    private void writeInventoryVerifyRecord(InventoryVerifyRecord record){
        writeInventoryVerifyRecord(record,null);
    }

    /** 填充对账主记录 根据rpa库存  **/
    private InventoryVerifyRecord fillInventoryRecordWithStandardInventory(StandardInventory inventory,
                                                                           InventoryVerifyRecord record,
                                                                           String groupFlag){
        record = fillInventoryRecordWithStandardInventory(inventory, record);
        if (StringUtils.isNotBlank(groupFlag)){
            record.setGroupFlag(groupFlag);
        }
        return record;
    }
    /** 填充对账主记录 根据rpa库存  **/
    private InventoryVerifyRecord fillInventoryRecordWithStandardInventory(StandardInventory inventory,
                                                                           InventoryVerifyRecord record){
        if (record == null){
            record = new InventoryVerifyRecord();
        }
        record.setFactoryCode(inventory.getFactoryCode());
        record.setInventoryCode(inventory.getInventoryCode());
        record.setGoodsCode(inventory.getGoodsCode());
        record.setStandardAvailableQuantity(inventory.getAvailableQuantity());
        record.setStandardWithholdingQuantity(inventory.getWithholdingQuantity());
        record.setStandardFrozenQuantity(inventory.getFrozenQuantity());
        record.setStandardInspectQuantity(inventory.getInspectQuantity());
        record.setStandardUnrestrictedQuantity(inventory.getUnrestrictedQuantity());
        return record;
    }
    /** 如果rpa库存校验有问题 **/
    private InventoryVerifyRecord fillInventoryRecordWithStandardInventoryWithMsg(StandardInventory inventory,
                                                                                  InventoryVerifyRecord record,
                                                                                  String msg,
                                                                                  String groupFlag){
        if (record == null){
            record = new InventoryVerifyRecord();
        }
        fillInventoryRecordWithStandardInventory(inventory, record);
        if (StringUtils.isNotBlank(msg)){
            record.setMsg(msg);
            if (msg.contains("工厂编码")){
                record.setMsgCode(FailReasonEnum.WAREHOUSE_NOT_FOUND.getCode());
            }else if (msg.contains("货品编码")){
                record.setMsgCode(FailReasonEnum.GOODS_NOT_FOUND.getCode());
            }else if (msg.contains("数字格式")){
                record.setMsgCode(FailReasonEnum.QUANTITY_FORMAT_ILLEGAL.getCode());
            }else if (msg.contains("获取库存统计结果")){
                record.setMsgCode(FailReasonEnum.INVENTORY_NOT_EXIST.getCode());
            }
            record.setVerifyStatus(VERIFY_FAIL);
            record.setWithholdingQuantityVerifyStatus(VERIFY_FAIL);
            record.setFrozenQuantityVerifyStatus(VERIFY_FAIL);
            record.setInspectQuantityVerifyStatus(VERIFY_FAIL);
            record.setAvailableQuantityVerifyStatus(VERIFY_FAIL);
            record.setUnrestrictedQuantityVerifyStatus(VERIFY_FAIL);
        }
        if (StringUtils.isNotBlank(groupFlag)){
            record.setGroupFlag(groupFlag);
        }
        return record;
    }

    /** 填充0 **/
    void fillQueryInventorySumQuantityResult(QueryInventorySumQuantityResult result){
        if (result == null){
            return;
        }
        if (result.getAvailableQuantity() == null){
            result.setAvailableQuantity(0L);
        }
        if (result.getWithholdingQuantity() == null){
            result.setWithholdingQuantity(0L);
        }
        if (result.getFrozenQuantity() == null){
            result.setFrozenQuantity(0L);
        }
        if (result.getTotalQuantity() == null){
            result.setTotalQuantity(0L);
        }
    }
    /** 用我们中台的库存 - rpa库存 * 1000 **/
    private Long subtract(String logicQuantity ,String rpaQuantity){
        BigDecimal logicDecimal = BigDecimal.ZERO;
        BigDecimal rpaDecimal = BigDecimal.ZERO;
        if (StringUtils.isNotBlank(logicQuantity)){
            logicDecimal = new BigDecimal(logicQuantity);
        }
        if (StringUtils.isNotBlank(rpaQuantity)){
            //rpa库存 放大1000
            rpaDecimal = new BigDecimal(rpaQuantity.trim()).movePointRight(1000);
        }
        return logicDecimal.subtract(rpaDecimal).longValue();
    }
    /** 用我们中台的库存  - rpa库存 * 1000  **/
    private Long subtract(Long logicQuantity ,String rpaQuantity){
        BigDecimal logicDecimal = BigDecimal.ZERO;
        BigDecimal rpaDecimal = BigDecimal.ZERO;
        if (logicQuantity != null){
//            logicDecimal = new BigDecimal(logicQuantity).movePointLeft(3);
            logicDecimal = new BigDecimal(logicQuantity);
        }
        if (StringUtils.isNotBlank(rpaQuantity)){
            //rpa库存 放大1000
            rpaDecimal = new BigDecimal(rpaQuantity.trim()).movePointRight(3);
//            rpaDecimal = new BigDecimal(rpaQuantity.trim());
        }
        return logicDecimal.subtract(rpaDecimal).longValue();
    }

    /** rpa库存 -  用我们中台的库存 /1000   **/
    private String getDiff(Long logicQuantity ,String rpaQuantity){
        BigDecimal logicDecimal = BigDecimal.ZERO;
        BigDecimal rpaDecimal = BigDecimal.ZERO;
        if (logicQuantity != null){
            logicDecimal = new BigDecimal(logicQuantity).movePointLeft(3);
        }
        if (StringUtils.isNotBlank(rpaQuantity)){
            //rpa库存
            rpaDecimal = new BigDecimal(rpaQuantity.trim());
        }
        return rpaDecimal.subtract(logicDecimal).toString();
    }


    private Long getUnrestrictedQuantity(Long totalQuantity,Long frozenQuantity,Long inspectQuantity){
        return totalQuantity - frozenQuantity - inspectQuantity;
    }

    /** 状态 **/
    private Integer getStatus(Long diff){
        return diff == 0L ? 1 : 0;
    }
    private Integer getStatus(String diff){
        return BigDecimal.ZERO.compareTo(new BigDecimal(diff)) == 0 ? 1 : 0;
    }
    /** 总体校验状态 **/
    private void setVerifyStatus(InventoryVerifyRecord record){
        boolean flag = record.getAvailableQuantityVerifyStatus() == VERIFY_SUCCESS
                && record.getWithholdingQuantityVerifyStatus() == VERIFY_SUCCESS
                && record.getFrozenQuantityVerifyStatus() == VERIFY_SUCCESS
                && record.getInspectQuantityVerifyStatus() == VERIFY_SUCCESS
                && record.getUnrestrictedQuantityVerifyStatus() == VERIFY_SUCCESS;
        record.setVerifyStatus(flag ? VERIFY_SUCCESS : VERIFY_FAIL);
    }

    /**数量缩小1000倍 **/
    private String zoomOutOneThousand(Long quantity){
        if (quantity == null){
            return null;
        }
        return new BigDecimal(quantity).movePointLeft(3).toString();
    }

    /** 校验数字 非数字false **/
    private boolean checkQuantity(String quantity){
        return NumberUtils.isCreatable(quantity.trim());
    }

    private <T> T convert(Object data,Class<T> tClass){
        if (data == null){
            return null;
        }
        return JSON.parseObject(JSON.toJSONString(data),tClass);
    }
    private <T> List<T> convert(List<?> dataList,Class<T> tClass){
        if (CollectionUtils.isEmpty(dataList)){
            return null;
        }
        return JSONArray.parseArray(JSON.toJSONString(dataList),tClass);
    }

    private boolean isAllZero(StandardInventory inventory){
        return BigDecimal.ZERO.compareTo(new BigDecimal(inventory.getAvailableQuantity())) == 0 &&
                BigDecimal.ZERO.compareTo(new BigDecimal(inventory.getWithholdingQuantity())) == 0 &&
                BigDecimal.ZERO.compareTo(new BigDecimal(inventory.getFrozenQuantity())) == 0 &&
                BigDecimal.ZERO.compareTo(new BigDecimal(inventory.getInspectQuantity())) == 0 &&
                BigDecimal.ZERO.compareTo(new BigDecimal(inventory.getUnrestrictedQuantity())) == 0;
    }

    // 初始化0库存
    private QueryInventorySumQuantityResult init(String warehouseAreaId,String warehouseId,String goodsId){
        QueryInventorySumQuantityResult result = new QueryInventorySumQuantityResult();
        result.setWarehouseId(warehouseAreaId);
        result.setWarehouseId(warehouseId);
        result.setGoodsId(goodsId);
        result.setAvailableQuantity(0L);
        result.setWithholdingQuantity(0L);
        result.setInspectQuantity(0L);
        result.setTotalQuantity(0L);
        result.setFrozenQuantity(0L);
        return  result;
    }
}
